package com.zoo.diannaopeijian.service.impl;

import com.zoo.diannaopeijian.domain.Entryitem;
import com.zoo.diannaopeijian.domain.Entryrecord;
import com.zoo.diannaopeijian.domain.Stock;
import com.zoo.diannaopeijian.service.EntryItemService;
import com.zoo.diannaopeijian.service.EntryService;
import com.zoo.diannaopeijian.service.EntryrecordService;
import com.zoo.diannaopeijian.service.StockService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.beans.Transient;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by zx583 on 2018-01-27.
 */
@Service
public class EntryServiceImpl implements EntryService {
    @Resource
    private EntryItemService entryItemService;
    @Resource
    private EntryrecordService entryrecordService;
    @Resource
    private StockService stockService;

    @Transactional
    @Override
    public boolean EntryWares(Integer staffid, List<Entryitem> entryItems) {
        // 创建入货记录
        Entryrecord entryrecord = new Entryrecord();
        entryrecord.setStaffid(staffid);
        entryrecord.setEntryrecorditime(new Date());

        boolean result = entryrecordService.insertEntryRecord(entryrecord);

        List<Stock> stocks = new ArrayList<>();
        // 插入入货记录项,同时创建库存对象
        for (Entryitem item : entryItems) {
            item.setEntryrecordid(entryrecord.getEntryrecordid());
            stocks.add(Stock.buildStock(item));
        }

        result = result && entryItemService.insertEntryItems(entryItems);

        // 修改库存
        result = result && stockService.addStocks(stocks);

        return result;
    }

    @Transactional
    @Override
    public boolean ReEntryWares(List<Entryitem> entryItems) {
        // 删除原本的进货项
        Entryitem entryitem = new Entryitem();
        entryitem.setEntryrecordid(entryItems.get(0).getEntryrecordid());
        List<Entryitem> itemsBeDelete = entryItemService.deleteEntryItems(entryitem);

        boolean result = true;

        // 修改库存
        // 构造要修改的库存对象
        List<Stock> stocks = new ArrayList<>();
        for (Entryitem item : itemsBeDelete) {
            stocks.add(Stock.buildStock(item));
        }
        result = result && stockService.reduceStocks(stocks);

        // 插入入货记录项
        result = result && entryItemService.insertEntryItems(entryItems);

        // 修改库存
        stocks.clear();
        for (Entryitem item : entryItems) {
            stocks.add(Stock.buildStock(item));
        }
        result = result && stockService.addStocks(stocks);

        if (!result) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return result;
    }
}
